<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编码" prop="billcode">
        <el-input
          v-model="queryParams.billcode"
          placeholder="请输入订单编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单日期" prop="billdate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.billdate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择订单日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约时间" prop="bookdate">
        <el-date-picker clearable size="small"
                        v-model="queryParams.bookdate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户" prop="gid">
        <el-select v-model="queryParams.gid" filterable placeholder="请选择客户" clearable size="small">
          <el-option
            v-for="guest in guestList"
            :key="guest.gid"
            :label="guest.name"
            :value="guest.gid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="货品" prop="goodsid">
        <el-select v-model="queryParams.goodsid" filterable placeholder="请选择货品" clearable size="small">
          <el-option
            v-for="goods in goodsList"
            :key="goods.goodsid"
            :label="goods.name+'('+goods.unitname+')'"
            :value="goods.goodsid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="billstate">
        <el-input
          v-model="queryParams.billstate"
          placeholder="请输入单据状态"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成否" prop="isover">
        <el-select v-model="queryParams.isover" placeholder="请选择完成否">
          <el-option
            v-for="dict in dict.type.bill_isover"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:orderbill:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:orderbill:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:orderbill:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:orderbill:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:orderbill:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderbillList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="订单编码" prop="billcode"/>
      <el-table-column label="订单日期" prop="billdate" width="180"/>
      <el-table-column label="预约时间" prop="bookdate" width="180"/>
      <el-table-column label="客户" prop="gid">
        <template slot-scope="scope">
          <span>{{ guesMatching(scope.row.gid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货品" prop="goodsid">
        <template slot-scope="scope">
          <span>{{ goodsMatching(scope.row.goodsid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="大约数量" prop="quantity"/>
      <el-table-column label="联系电话" prop="tel"/>
      <el-table-column label="单据状态" prop="billstate"/>
      <el-table-column label="完成否" prop="isover">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bill_isover" :value="scope.row.isover"/>
        </template>
      </el-table-column>
      <el-table-column label="清运地址" prop="address"/>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:orderbill:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:orderbill:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div ref="formContent">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编码" prop="billcode">
              <el-input :disabled="form.billid!=null" v-model="form.billcode" placeholder="请输入订单编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时间" prop="bookdate">
              <el-date-picker :disabled="form.billid!=null" clearable size="small"
                              v-model="form.bookdate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择订单日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="gid">
              <el-select v-model="form.gid" filterable placeholder="请选择客户" clearable>
                <el-option
                  v-for="guest in guestList"
                  :key="guest.gid"
                  :label="guest.name"
                  :value="guest.gid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="货品" prop="goodsid">
              <el-select v-model="form.goodsid" filterable placeholder="请选择货品" clearable>
                <el-option
                  v-for="goods in goodsList"
                  :key="goods.goodsid"
                  :label="goods.name+'('+goods.unitname+')'"
                  :value="goods.goodsid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="大约数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入大约数量"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="billstate">
              <el-input v-model="form.billstate" placeholder="请输入单据状态"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成否" prop="isover">
              <el-select v-model="form.isover" placeholder="请选择完成否">
                <el-option
                  v-for="dict in dict.type.bill_isover"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="清运地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入清运地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="primary" @click="printHandle">打 印</el-button>
        <el-button @click="cancel">取 消</el-button>
        
      </div>
    </el-dialog>

    <!-- 订单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderbill, getOrderbill, delOrderbill, addOrderbill, updateOrderbill, getCode } from "@/api/system/orderbill";
import {listGuestAll} from "@/api/system/guest";
import {listGoodsAll} from "@/api/system/goods";
import {getToken} from "@/utils/auth";
import html2canvas from "html2canvas";
import printJS from "print-js";
export default {
  name: "Orderbill",
  dicts: ['bill_isover'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderbillList: [],
      //货品列表
      goodsList: [],
      //客户列表
      guestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billcode: null,
        bookdate: null,
        gid: null,
        goodsid: null,
        quantity: null,
        tel: null,
        billstate: null,
        isover: null,
        address: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billcode: [
          {required: true, message: "订单编码不能为空", trigger: "blur"}
        ],
        bookdate: [
          {required: true, message: "预约时间不能为空", trigger: "blur"}
        ],
        gid: [
          {required: true, message: "客户ID不能为空", trigger: "blur"}
        ],
        goodsid: [
          {required: true, message: "货品ID不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        createBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        address:[
          {required: true, message: "清运地址不能为空", trigger: "blur"}
        ],
        tel:[
          {
            validator: function (rule, value, callback) {
              if (/(^(\d{3,4}-)?\d{7,8})$|(1[3|5|7|8]\d{9})/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      // 订单导入参数
      upload: {
        // 是否显示弹出层（货品）
        open: false,
        // 弹出层标题（货品）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/orderbill/importData"
      },
    };
  },
  created() {
    this.getList();
    this.getGuesList();
    this.getGoodsList();
  },
  methods: {
    getGoodsList() {
      listGoodsAll().then(response => {
        this.goodsList = response.data;
      })
    },
    getGuesList() {
      listGuestAll().then(response => {
        this.guestList = response.data;
      })
    },
    guesMatching(gid) {
      let name = "-";
      this.guestList.map(item => {
        if (gid == item.gid) {
          name = item.name;
          return
        }
      })
      return name;
    },
    goodsMatching(goodsid) {
      let name = "-";
      this.goodsList.map(item => {
        if (goodsid == item.goodsid) {
          name = item.name + '(' + item.unitname + ')';
          return
        }
      })
      return name;
    },
    getCode() {
      getCode().then(response => {
        this.form.billcode = response.data;
      })
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrderbill(this.queryParams).then(response => {
        this.orderbillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billid: null,
        billcode: null,
        billdate: null,
        gid: null,
        goodsid: null,
        quantity: null,
        tel: null,
        billstate: null,
        isover: null,
        address: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.billid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
      this.getCode()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const billid = row.billid || this.ids
      getOrderbill(billid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.billid != null) {
            updateOrderbill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderbill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const billids = row.billid || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + billids + '"的数据项？').then(function () {
        return delOrderbill(billids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orderbill/export', {
        ...this.queryParams
      }, `orderbill_${new Date().getTime()}.xlsx`)
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "账户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/orderbill/importTemplate', {}, `订单导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    printHandle() {
      const style = ['@page {margin:0;size: A4} html {margin: 4mm;}']
      html2canvas(this.$refs.formContent, {
        backgroundColor: null,
        useCORS: true,
        windowHeight: document.body.scrollHeight,
      }).then((canvas) => {
        const url = canvas.toDataURL();
        this.img = url;
        printJS({
          printable: url,
          type: "image",
          style,
        });
      });
    },
  }
};
</script>
